package com.weilive.platform.gate.json.handler;

import org.springframework.stereotype.Service;

import com.weilive.core.netty.NettyErrors;
import com.weilive.core.protocol.json.JsonRequest;
import com.weilive.core.protocol.json.JsonRequestHandler;
import com.weilive.core.protocol.json.JsonResponse;
import com.weilive.core.utils.MD5Utils;
import com.weilive.platform.PlatformConstants;
import com.weilive.platform.PlatformErrors;
import com.weilive.platform.cache.app.AppManager;
import com.weilive.platform.cache.app.AppObj;
import com.weilive.platform.cache.user.UserManager;
import com.weilive.platform.cache.user.UserObj;
import com.weilive.platform.gate.json.protocol.SSA_PlatUserLogin;
import com.weilive.platform.gate.json.protocol.SSQ_PlatUserLogin;

@Service
public class SSQ_PlatUserLogin_JsonHandler extends JsonRequestHandler {

	public Class<?> getRequestType() {
		return SSQ_PlatUserLogin.class;
	}

	public Class<?> getResponseType() {
		return SSA_PlatUserLogin.class;
	}

	private boolean checkSign(SSQ_PlatUserLogin params, String secret) throws Exception {
		long delta = System.currentTimeMillis() - params.date;
		if (delta > PlatformConstants.SERVER_SIGN_VALID_INTERVAL
				|| delta < -PlatformConstants.SERVER_SIGN_VALID_INTERVAL) {
			return false;
		}
		String sign = MD5Utils
				.encryptToHex(secret + params.date + MD5Utils.encryptToHex(params.uin + params.token + params.app_id));
		return params.sign.equals(sign);
	}

	public JsonResponse handleRequest(JsonRequest request) throws Exception {
		SSQ_PlatUserLogin params = (SSQ_PlatUserLogin) request.getData();

		// 检测参数
		if (params.date == null || params.sign == null || params.uin == null || params.token == null
				|| params.app_id == null) {
			return createErrorResponse(NettyErrors.BAD_REQUEST);
		}
		Long userId = UserManager.getUserId(params.uin, params.app_id, params.token);
		if (userId == null) {
			return createErrorResponse(NettyErrors.BAD_REQUEST);
		}
		// 检测游戏
		AppObj app = AppManager.getApp(params.app_id);
		if (app == null) {
			return createErrorResponse(PlatformErrors.APP_NOT_EXIST);
		}
		// 检测签名
		if (checkSign(params, app.info.secret) == false) {
			return createErrorResponse(PlatformErrors.SERVER_SIGN_FAILED);
		}
		UserObj user = UserManager.getUser(userId);
		if (user == null) {
			return createErrorResponse(PlatformErrors.USER_NOT_EXIST);
		}
		if (!user.checkToken(params.app_id, params.token)) {
			return createErrorResponse(PlatformErrors.INVALID_TOKEN);
		}
		SSA_PlatUserLogin response = new SSA_PlatUserLogin();
		response.user_id = userId;
		response.account = user.getAccount();
		return JsonResponse.create(response);
	}

}
